package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IRegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("user")
public class RegisterController {

    @Reference(timeout = 3000,check = false)
    private IKaptchaService iKaptchaService;

    @Reference(timeout = 3000, check = false)
    private IRegisterService iRegisterService;

    /**
     * 用户注册
     * @param map
     * @return
     */
    @Anoymous
    @PostMapping("register")
    public ResponseData register(@RequestBody Map<String,String> map, HttpServletRequest request) {
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");

        //判断验证码
        String kaptchaUuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setUuid(kaptchaUuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getCode())){
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }

        //添加用户信息
        UserRegisterRequest registerRequest = new UserRegisterRequest();
        registerRequest.setUserName(userName);
        registerRequest.setUserPwd(userPwd);
        registerRequest.setEmail(email);
        UserRegisterResponse registerResponse = iRegisterService.register(registerRequest);
        if (registerResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(registerResponse.getMsg());
    }

    /**
     * 注册邮箱激活
     * @return
     */
    @Anoymous
    @GetMapping("verify")
    public ResponseData verify(String uid, String username){
        UserVerifyRequest request = new UserVerifyRequest();
        request.setUuid(uid);
        request.setUserName(username);
        UserVerifyResponse response = iRegisterService.verify(request);
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}
